#!/usr/bin/env node

/**
 * 清理脚本 - 用于清理可能残留的开发进程
 * 解决 npm run electron-dev 第二次运行无响应的问题
 */

const { exec } = require('child_process');
const os = require('os');

function killProcessByPort(port) {
  return new Promise((resolve) => {
    const platform = os.platform();
    let command;
    
    if (platform === 'win32') {
      command = `netstat -ano | findstr :${port}`;
    } else {
      command = `lsof -ti:${port}`;
    }
    
    exec(command, (error, stdout) => {
      if (error || !stdout.trim()) {
        console.log(`端口 ${port} 未被占用`);
        resolve();
        return;
      }
      
      if (platform === 'win32') {
        // Windows处理
        const lines = stdout.trim().split('\n');
        const pids = lines.map(line => {
          const parts = line.trim().split(/\s+/);
          return parts[parts.length - 1];
        }).filter(pid => pid && !isNaN(pid));
        
        pids.forEach(pid => {
          exec(`taskkill /F /PID ${pid}`, (killError) => {
            if (!killError) {
              console.log(`已终止进程 PID: ${pid}`);
            }
          });
        });
      } else {
        // macOS/Linux处理
        const pids = stdout.trim().split('\n').filter(pid => pid && !isNaN(pid));
        pids.forEach(pid => {
          exec(`kill -9 ${pid}`, (killError) => {
            if (!killError) {
              console.log(`已终止进程 PID: ${pid}`);
            }
          });
        });
      }
      
      resolve();
    });
  });
}

function killElectronProcesses() {
  return new Promise((resolve) => {
    const platform = os.platform();
    let command;
    
    if (platform === 'win32') {
      command = 'tasklist | findstr electron';
    } else {
      command = 'ps aux | grep electron | grep -v grep';
    }
    
    exec(command, (error, stdout) => {
      if (error || !stdout.trim()) {
        console.log('未发现残留的 Electron 进程');
        resolve();
        return;
      }
      
      if (platform === 'win32') {
        // Windows处理
        exec('taskkill /F /IM electron.exe', (killError) => {
          if (!killError) {
            console.log('已清理 Electron 进程');
          }
          resolve();
        });
      } else {
        // macOS/Linux处理
        exec('pkill -f electron', (killError) => {
          if (!killError) {
            console.log('已清理 Electron 进程');
          }
          resolve();
        });
      }
    });
  });
}

async function cleanup() {
  console.log('开始清理开发环境...');
  
  // 清理端口8080
  await killProcessByPort(8080);
  
  // 清理Electron进程
  await killElectronProcesses();
  
  console.log('清理完成！');
}

if (require.main === module) {
  cleanup().catch(console.error);
}

module.exports = { cleanup, killProcessByPort, killElectronProcesses };